package com.igeekhome.ccs.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import com.igeekhome.ccs.biz.Impl.CustomerServiceBizImpl;
import com.igeekhome.ccs.util.md5;

import java.util.Map;

@Controller
//@RequestMapping("/index")
public class IndexController {
    @Autowired
    CustomerServiceBizImpl csbi;
    @PostMapping("/login")
    @ResponseBody
    public String doLogin(@RequestBody Map<String, String> map){
        //        依靠shiro的subject 来实现登陆的逻辑

        String username = map.get("username");
        String password = map.get("password");

        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username,password);

        try {
            subject.login(token);
        } catch (UnknownAccountException uae) {
            return "未知账户";
        } catch (IncorrectCredentialsException ice) {
            return "密码不正确";
        } catch (LockedAccountException lae) {
            return "账户已锁定";
        } catch (ExcessiveAttemptsException eae) {
            return "用户名或密码错误次数过多";
        } catch (AuthenticationException ae) {
            return ae.getMessage();
        }
        if(subject.isAuthenticated()){
            return "登陆成功";
        }else{
            token.clear();
            return "登陆失败" ;
        }
    }

    @PostMapping("/register")
    @ResponseBody
    public String doRegist(@RequestBody Map<String, String> map){
        //        依靠shiro的subject 来实现登陆的逻辑

        String username = map.get("username");
        String password = map.get("password");

        password=md5.MD5Pwd(username,password);
        int a= csbi.regist(username,password);
        if (a<0){
            return "注册失败，用户名已存在";
        }
        return "注册成功";
    }


}
